package com.example.woke1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.silent.handle.CharacterParser;
import com.silent.handle.PinyinComparator;
import com.silent.handle.SideBar;
import com.silent.handle.SideBar.OnTouchingLetterChangedListener;
import com.woke.data.Data_myfriendb;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;

import cn.xl.xxl.imagecache.ImageLoader;

public class FriendborrowActivity extends Activity {

	private ListView mListView;
	private MyApp application;
	private ArrayList<Data_myfriendb> datalist = new ArrayList<Data_myfriendb> ();
	private ImageLoader imageLoader;
	private ArrayList<String> friendlist = new ArrayList<String> ();
	private Myadapter adapter;
	private Intent intent;
	private RelativeLayout mBar;
	private ArrayList<String> chenckedf;//��ѡ������

	/**
	 * ����ת����ƴ������
	 */
	private CharacterParser characterParser;
	/**
	 * ���ƴ��������ListView����������
	 */
	private PinyinComparator pinyinComparator;
	private SideBar sideBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_friendborrow);

		imageLoader = new ImageLoader (this);
		intent = getIntent ();
		chenckedf = intent.getStringArrayListExtra ("chenckedf");
		application = (MyApp) getApplication ();
		intview ();


	}

	@Override
	protected void onDestroy() {
		imageLoader.clearCache ();
		imageLoader.clearMemoryCache ();
		super.onDestroy ();
	}

	private void intview() {
		mListView = (ListView) findViewById (R.id.avfriendbor_listview);
		// ʵ����תƴ����
		characterParser = CharacterParser.getInstance ();
		pinyinComparator = new PinyinComparator ();
		sideBar = (SideBar) findViewById (R.id.sidrbar);
		// �����Ҳഥ������
		sideBar.setOnTouchingLetterChangedListener (new OnTouchingLetterChangedListener () {

			@Override
			public void onTouchingLetterChanged(String s) {
				// ����ĸ�״γ��ֵ�λ��
				Log.e ("" + s, "" + s.charAt (0));
				if (adapter != null) {
					int position = adapter.getPositionForSection (s.charAt (0));
					if (position != - 1) {
						mListView.setSelection (position);
					}
				}

			}
		});

		mEcarno = (EditText) findViewById (R.id.avborrowf_edit_search);
		mEcarno.addTextChangedListener (watcher);

		mBar = (RelativeLayout) findViewById (R.id.avborrowf_progress_bar);
		findViewById (R.id.avfriendbor_image_back).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View view) {
				finish ();
			}
		});
		findViewById (R.id.avfriendbor_text_ok).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				for (int i = 0; i < datalist.size (); i++) {
					if (datalist.get (i).type == 1) {
						friendlist.add (datalist.get (i).userid);
//						str = str + datalist.get(i).userid+strd;
					}
				}
				intent.putExtra ("datalist", friendlist);
				setResult (403, intent);
				finish ();
			}
		});
		getfriendlist ();
	}

	private TextWatcher watcher = new TextWatcher () {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			String trim = "" + mEcarno.getText ().toString ().trim ();
			if (trim.equals ("")) {
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
			} else {
				int length = trim.length ();
//	    		Log.e("length", ""+length);
				for (int i = 0; i < datalist.size (); i++) {
					if (datalist.get (i).name.length () >= length) {
						if (datalist.get (i).name.substring (0, length).endsWith (trim)) {
							mListView.setSelection (i);
							return;
						}
					}
				}
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
			}
		}
	};
	private EditText mEcarno;

	private void getfriendlist() {
		if (application.getDatas_load () == null) return;
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (FriendborrowActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "myFridenlist");
		params.put ("userid", application.getDatas_load ().getId ());
		Log.e ("params", params.toString ());
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("�ϴ�", "�ֻ��" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject object = response.getJSONObject ("data");
						JSONArray jsonArray = object.getJSONArray ("data");
						for (int i = 0; i < jsonArray.length (); i++) {
							int type = 0;
							JSONObject object2 = jsonArray.getJSONObject (i);
							String head = object2.getString ("head");
							String userid = object2.getString ("userid");
							String name = object2.getString ("name");
							if (chenckedf.size () > 0) {
								for (int j = 0; j < chenckedf.size (); j++) {
									if (chenckedf.get (j).equals (userid)) {
										type = 1;
									}
								}
							}
							String shouzimu = "";

							// ����ת����ƴ��
							String pinyin = characterParser.getSelling (name);
							String sortString = pinyin.substring (0, 1).toUpperCase ();

							// ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
							if (sortString.matches ("[A-Z]")) {
								shouzimu = sortString.toUpperCase ();
							} else {
								shouzimu = "#";
							}

							Data_myfriendb list = new Data_myfriendb (head, userid, name, type, shouzimu);
							datalist.add (list);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}


				if (datalist.size () > 0) {
					// ���a-z��������Դ���
					Collections.sort (datalist, pinyinComparator);
					adapter = new Myadapter ();
					mListView.setAdapter (adapter);
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
//				Log.e("�ϴ�", "�ֻ��ʧ��"+responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mBar.setVisibility (View.GONE);
			}
		});
	}

	class Myadapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datalist.size ();
		}

		@Override
		public Object getItem(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		@Override
		public long getItemId(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		public class Holder {
			ImageView iconcheck;
			ImageView usericon;
			TextView textname, tvLetter;
		}

		/**
		 * ���ListView�ĵ�ǰλ�û�ȡ���������ĸ��Char asciiֵ
		 */
		public int getSectionForPosition(int position) {
			return datalist.get (position).shouzimu.charAt (0);
		}

		/**
		 * ��ݷ��������ĸ��Char asciiֵ��ȡ���һ�γ��ָ�����ĸ��λ��
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < getCount (); i++) {
				String sortStr = datalist.get (i).shouzimu;
				char firstChar = sortStr.toUpperCase ().charAt (0);
				if (firstChar == section) {
					return i;
				}
			}

			return - 1;
		}


		@Override
		public View getView(final int position, View convertView, ViewGroup viewgroup) {
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder ();
				convertView = getLayoutInflater ().inflate (R.layout.friendb_item_layout, null);
				holder.usericon = (ImageView) convertView.findViewById (R.id.item_friendb_icon);
				holder.iconcheck = (ImageView) convertView.findViewById (R.id.item_friendb_iconcheck);
				holder.textname = (TextView) convertView.findViewById (R.id.item_friendb_text);
				holder.tvLetter = (TextView) convertView.findViewById (R.id.catalog);
				convertView.setTag (holder);
			} else {
				holder = (Holder) convertView.getTag ();
			}

			final Data_myfriendb myfriend = datalist.get (position);
			// ���position��ȡ���������ĸ��Char asciiֵ
			int section = getSectionForPosition (position);

			// ���ǰλ�õ��ڸ÷�������ĸ��Char��λ�� ������Ϊ�ǵ�һ�γ���
			if (position == getPositionForSection (section)) {
				holder.tvLetter.setVisibility (View.VISIBLE);
				holder.tvLetter.setText (myfriend.shouzimu);
			} else {
				holder.tvLetter.setVisibility (View.GONE);
			}
			holder.textname.setText (myfriend.name);
			imageLoader.DisplayImage ("http://" + myfriend.head, holder.usericon, false, true, true, 0);
			if (myfriend.type == 0) {
				holder.iconcheck.setImageDrawable (getResources ().getDrawable (R.drawable.item_imag_friendb));
			} else {
				holder.iconcheck.setImageDrawable (getResources ().getDrawable (R.drawable.item_imag_friendb1));
			}
			holder.iconcheck.setOnClickListener (new OnClickListener () {

				@Override
				public void onClick(View v) {
					if (datalist.get (position).type == 1) {
						datalist.get (position).type = 0;
//						friendlist.remove(i);
					} else {
						datalist.get (position).type = 1;
//						friendlist.add(datalist.get(i).userid);
					}
					adapter.notifyDataSetChanged ();
				}
			});
			return convertView;
		}

	}

}
